package com.liangtian.mdm.system.file.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.system.business.dao.SysBusinessDao;
import com.liangtian.mdm.system.business.model.SysBusiness;
import com.liangtian.mdm.system.file.model.SysFile;
import com.liangtian.mdm.system.file.service.SysFileService;
import com.liangtian.mdm.util.RequestUtils;
import com.liangtian.mdm.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/file")
public class SysFileController extends BaseController {

    @Autowired
    SysFileService sysFileService;
    @Autowired
    private SysBusinessDao sysBusinessDao;

    /**
     * 附件上传
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public ResultObject upload(HttpServletRequest request, HttpServletResponse response) {
        ResultObject result = null;
        Map<String, Object> resMap = sysFileService.insertFile(request, null);
        boolean success = (boolean) resMap.get("IsSuccess");
        if (success) {
            result = new ResultObject(success, "上传成功");
        } else {
            result = new ResultObject(success, "上传失败");
        }
        return result;
    }

    @RequestMapping(value = "/queryFiles", method = RequestMethod.POST)
    @ResponseBody
    public String queryFileBySurvey(HttpServletRequest request) {
        Map<String, Object> param = RequestUtils.paramToMap(request);
        List<SysFile> fileLst = sysFileService.queryFileBySurvey(param);
        return JSON.toJSONString(fileLst);
    }

    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/queryAllFiles", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject queryAllFiles(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request);
        System.out.println(paramMap);
        PageInfo pageInfo = sysFileService.queryFilesPageBySurvey(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/queryAllSysContentFiles", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject queryAllSysContentFiles(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request);
        System.out.println(paramMap);
        SysBusiness sysb = new SysBusiness();
        sysb.setBusTable("DOC_CMS_CONTENT");
        List<SysBusiness> bList = sysBusinessDao.queryBusByContion(sysb);//查询业务类型
        String bus_id = bList.get(0).getBusId();//业务类型
        paramMap.put("surveyType", bus_id);
        PageInfo pageInfo = sysFileService.queryFilesPageBySurvey(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }
	
	/*@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/queryFiles", method = RequestMethod.POST)
    @ResponseBody
	public JSONObject queryFilesBySurvey(HttpServletRequest request){
		Map<String,Object> paramMap = RequestUtils.paramToMap(request);

		PageInfo pageInfo = sysFileService.queryFileBySurvey(paramMap);
		List l = pageInfo.getList();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", l);
		jsonObject.put("total", pageInfo.getTotal());
		return jsonObject;
	}*/

    @RequestMapping(value = "/queryDownload", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject queryDownload(HttpServletRequest request) {
        Map<String, Object> param = RequestUtils.paramToMap(request);
        List<SysFile> sysFileLst = sysFileService.queryFilesBySurvey(param);
        boolean b = false;
        for (SysFile sysFile : sysFileLst) {
            if (!"".equals(sysFile.getFileName())) {
                b = true;
                break;
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("download", b);//JSONArray
        return jsonObject;
    }


    /**
     * 附件下载
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "download", method = RequestMethod.POST)
    @ResponseBody
    public void download(HttpServletResponse response, HttpServletRequest request) {
        Map<String, Object> param = RequestUtils.paramToMap(request);
        String fileId = (String) param.get("fileId");
        SysFile sysFile = null;
        List<SysFile> sysFileLst = null;
        if (!StringUtil.isBlank(fileId))
            sysFile = sysFileService.queryFileById(fileId);
        else
            sysFileLst = sysFileService.queryFileBySurvey(param);

        String filePath = null;
        String fileName;
        try {
            if (null != sysFile) {
                filePath = sysFile.getFilePath();
                fileName = sysFile.getFileName();
            } else {
                filePath = sysFileLst.get(0).getFilePath();
                fileName = sysFileLst.get(0).getFileName();
            }
            InputStream inStream = new FileInputStream(filePath);
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            OutputStream output = response.getOutputStream();
            while ((len = inStream.read(b)) > 0)
                output.write(b, 0, len);

            output.flush();
            output.close();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//	/**
//	 * 附件下载
//	 * @param response
//	 * @param request
//	 */
//	@RequestMapping(value = "downloadSysContent", method = RequestMethod.POST)
//    @ResponseBody
//    public void downloadSysContent(HttpServletResponse response,HttpServletRequest request){
//		Map<String, Object> param = RequestUtils.paramToMap(request);
//		String fileId = (String) param.get("fileId");
//		SysFile sysFile = null;
//		List<SysFile> sysFileLst = null;
//		if(!StringUtils.isBlank(fileId))
//			sysFile = sysFileService.queryFileById(fileId);
//		else 
//    	   sysFileLst =sysFileService.queryFileBySurvey(param);
//    	
//    	String filePath=null;
//    	String fileName;
//    	try {
//    		if(null != sysFile){
//    			filePath = sysFile.getFilePath();
//    			fileName = sysFile.getFileName();
//    		}else{
//    			filePath = sysFileLst.get(0).getFilePath();
//    			fileName = sysFileLst.get(0).getFileName();
//    		}
//    		InputStream inStream = new FileInputStream(filePath);
//    		if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
//    			     fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
//    		}else{
//    			     fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
//    		}
//    		response.reset();
//    		response.setCharacterEncoding("UTF-8");
//    		response.setContentType("application/octet-stream; charset=UTF-8");
//    		response.addHeader("Content-Disposition",  "attachment;filename=\"" + fileName + "\"");
//    		// 循环取出流中的数据
//    		byte[] b = new byte[1024];
//    		int len;
//    		OutputStream output=response.getOutputStream();
//    		while ((len = inStream.read(b)) > 0)
//    			output.write(b, 0, len);
//    			
//    		output.flush();
//    		output.close();
//    		inStream.close();
//    	} catch (Exception e) {
//    		e.printStackTrace();
//    	} 
//	}


    /**
     * 附件下载
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "sysContentDownload", method = RequestMethod.POST)
    @ResponseBody
    public void sysContentDownload(HttpServletResponse response, HttpServletRequest request) {
        Map<String, Object> param = RequestUtils.paramToMap(request);
        String fileId = (String) param.get("fileId");
        String dataId = (String) param.get("dataId");
        param.put("dataId", dataId);
        SysFile sysFile = null;
        List<SysFile> sysFileLst = null;
        SysBusiness sysb = new SysBusiness();
        sysb.setBusTable("DOC_CMS_CONTENT");
        List<SysBusiness> bList = sysBusinessDao.queryBusByContion(sysb);//查询业务类型
        String bus_id = bList.get(0).getBusId();//业务类型
        param.put("surveyType", bus_id);
        if (!StringUtil.isBlank(fileId))
            sysFile = sysFileService.queryFileById(fileId);
        else
            sysFileLst = sysFileService.queryFileBySurvey(param);

        String filePath = null;
        String fileName;
        try {
            if (null != sysFile) {
                filePath = sysFile.getFilePath();
                fileName = sysFile.getFileName();
            } else {
                filePath = sysFileLst.get(0).getFilePath();
                fileName = sysFileLst.get(0).getFileName();
            }
            InputStream inStream = new FileInputStream(filePath);
    		/*String head = request.getHeader("User-Agent");
    		if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
    			     fileName = new String(fileName.getBytes("GBK"), "ISO8859-1");//IE浏览器
    		}else{
    			     fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
    		}*/
            fileName = new String(fileName.getBytes("GBK"), "ISO8859-1");//IE浏览器  刘晶带看
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            OutputStream output = response.getOutputStream();
            while ((len = inStream.read(b)) > 0)
                output.write(b, 0, len);

            output.flush();
            output.close();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 附件信息
     * @param response
     * @param request
     *//*
	@RequestMapping(value = "fileInfo", method = RequestMethod.POST)
    @ResponseBody
	public String fileInfo(String fileId){
		List<SysFile> fileLst=sysFileService.queryFileByDataId(fileId);
		return JSON.toJSONString(fileLst);
	}*/

    /**
     * 删除附件信息
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "delFile", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject delFile(String fileId) {
        ResultObject result = null;
        boolean success = true;
        SysFile file = sysFileService.queryFileById(fileId);
        sysFileService.delFileByPath(file);
        result = new ResultObject(success, "删除成功");
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getCodeXzFjById", method = RequestMethod.POST)
    @SuppressWarnings({"rawtypes", "unchecked"})
    public JSONObject getCodeXzFjById(HttpServletRequest request, SysFile file) {
        Map paramMap = RequestUtils.paramToMap(request, SysFile.class, false);
        PageInfo pageInfo = sysFileService.getCodeXzFjById(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    /**
     * 附件下载2
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "downloadForTXWL", method = RequestMethod.POST)
    @ResponseBody
    public void downloadForTXWL(HttpServletResponse response, HttpServletRequest request) {
        Map<String, Object> param = RequestUtils.paramToMap(request);
        String fileId = (String) param.get("fileId");
        SysFile sysFile = null;
        List<SysFile> sysFileLst = null;
        if (!StringUtil.isBlank(fileId))
            sysFile = sysFileService.queryFileById(fileId);
        else
            sysFileLst = sysFileService.queryFileBySurvey(param);

        String filePath = null;
        String fileName;
        try {
            if (null != sysFile) {
                filePath = sysFile.getFilePath();
                fileName = sysFile.getFileName();
            } else {
                filePath = sysFileLst.get(0).getFilePath();
                fileName = sysFileLst.get(0).getFileName();
            }
            InputStream inStream = new FileInputStream(filePath);
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
            } else {
                fileName = new String(fileName.getBytes("GBK"), "iso8859-1");//firefox浏览器
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream;charset=gbk");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            OutputStream output = response.getOutputStream();
            while ((len = inStream.read(b)) > 0)
                output.write(b, 0, len);

            output.flush();
            output.close();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
